import type {Recordable, UserInfo} from '@vben/types';

import {ref} from 'vue';
import {useRouter} from 'vue-router';

import {DEFAULT_HOME_PATH, LOGIN_PATH} from '@vben/constants';
import {resetAllStores, useAccessStore, useUserStore} from '@vben/stores';

import {notification} from 'ant-design-vue';
import {defineStore} from 'pinia';

import {getAccessCodesApi, getUserInfoApi, loginApi, logoutApi} from '#/api';
import {$t} from '#/locales';
// import { generateRoutes } from '@vben/utils';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;

      // 调用 loginApi，获取返回值 response
      const response = await loginApi(params);
      console.log(response)

      // 确保返回的 response 包含 accessToken
      if (!response || !response.accessToken) {
        throw new Error('返回值没有 accessToken');
      }

      // 从 response 中获取 accessToken
      const accessToken = response.accessToken;  // 不需要解构 response.accessToken，而是直接从 response 中解构

      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const [fetchUserInfoResult, accessCodes] = await Promise.all([
          fetchUserInfo(),
          getAccessCodesApi(),
        ]);

        userInfo = fetchUserInfoResult;
        userStore.setUserInfo(userInfo);
        // console.log("登录的时候设置进去的",userInfo)
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          // 如果有成功回调，执行它，否则跳转到默认首页
          onSuccess ? await onSuccess?.() : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
        }

        // 如果用户信息中有 realName，展示登录成功的提示
        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }

      }
    } catch (error) {
      console.error('登录失败:', error);
      notification.error({
        message: $t('authentication.loginFailed'),
        description: error.message,
      });
    } finally {
      loginLoading.value = false;
    }

    return { userInfo };
  }


  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);

    return userInfo;
  }


  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
